package com.powernobug.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @Author: 肖云戈
 * @CreateTime: 2024-08-29
 * @Description:
 */
@Configuration
public class MyBatisConfiguration {

    @Bean
    public DataSource dataSource() {
        DruidDataSource druid = new DruidDataSource();
        druid.setDriverClassName("com.mysql.jdbc.Driver");
        druid.setUrl("jdbc:mysql://127.0.0.1:3306/project1?useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true");
        druid.setUsername("root");
        druid.setPassword("12315");
        return druid;
    }

    @Bean
    public SqlSessionFactoryBean sessionFactory(DataSource dataSource) {

        // 注册配置分页插件
        Properties tempConfig = new Properties();
        tempConfig.put("helperDialect", "mysql");
        // 分页参数合法性处理
        tempConfig.put("reasonable", "true");
        PageInterceptor interceptor = new PageInterceptor();
        interceptor.setProperties(tempConfig);

        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setTypeHandlersPackage("com.powernobug.typehandler");
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setPlugins(interceptor);
        return sessionFactory;
    }

    @Bean
    public MapperScannerConfigurer mapperScanner() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setSqlSessionFactoryBeanName("sessionFactory");
        configurer.setBasePackage("com.powernobug.mapper");
        return configurer;
    }

    // 平台事务管理器
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
